﻿Namespace Cache
    ''' <summary>
    ''' Cache implementation by SCIEF
    ''' </summary>
    ''' <remarks></remarks>
    Public Class CacheExt
        ''' <summary>
        ''' Shared because we need the same instance every time we use the cache
        ''' </summary>
        ''' <remarks></remarks>
        Private Shared cache As System.Runtime.Caching.ObjectCache
        ''' <summary>
        ''' Shared because we need the same instance every time we use the cache
        ''' </summary>
        ''' <remarks></remarks>
        Private Shared policy As System.Runtime.Caching.CacheItemPolicy

        Public Sub New()
            cache = System.Runtime.Caching.MemoryCache.Default
            policy = New System.Runtime.Caching.CacheItemPolicy()
            policy.Priority = Runtime.Caching.CacheItemPriority.Default
        End Sub

        ''' <summary>
        ''' Add an object to the cache.
        ''' </summary>
        ''' <param name="objectName">Name of the object to cache</param>
        ''' <param name="cacheObject">The object to cache</param>
        ''' <remarks>By design, We store in cache for 60 seconds. (BDesjardins)</remarks>
        Public Shared Sub AddCacheObject(ByVal objectName As String, ByVal cacheObject As Object)
            'Testpoint: cache value setting
            policy.AbsoluteExpiration = DateTimeOffset.Now.AddSeconds(60.0)
            cache.Set(objectName, cacheObject, policy)
        End Sub
        ''' <summary>
        ''' Add an object to the cache, duration is Infinite
        ''' </summary>
        ''' <param name="objectName"></param>
        ''' <param name="cacheObject"></param>
        ''' <remarks>DateTimeOffset.MaxValue is the Infinite value</remarks>
        Public Shared Sub AddInfiniteCacheObject(ByVal objectName As String, ByVal cacheObject As Object)
            'Testpoint: cache value setting
            policy.AbsoluteExpiration = DateTimeOffset.MaxValue
            cache.Set(objectName, cacheObject, policy)
        End Sub
        ''' <summary>
        ''' Find the object in the cache, Return nothing if not found
        ''' </summary>
        ''' <param name="objectName">Name of the object</param>
        ''' <returns>The object in cache</returns>
        ''' <remarks>Don't forget to cast your object to the appropriate type</remarks>
        Public Shared Function GetCacheObject(ByVal objectName As String) As Object
            Return cache(objectName)
        End Function
        ''' <summary>
        ''' Remove each object from the cache
        ''' </summary>
        ''' <remarks></remarks>
        Public Shared Sub ClearCache()
            Dim items As List(Of KeyValuePair(Of String, Object)) = (From n In cache.AsParallel() Select n).ToList()
            For Each item As KeyValuePair(Of String, Object) In items
                cache.Remove(item.Key)
            Next
        End Sub

    End Class
End Namespace
